package one.stand.service.impl;

import lombok.extern.slf4j.Slf4j;
import one.stand.entity.WxNoticeEntity;
import one.stand.enums.LoginEnum;
import one.stand.enums.SendTypeEnum;
import one.stand.enums.WxSubscribeEnums;
import one.stand.model.CompanyModel;
import one.stand.model.ResultModel;
import one.stand.model.UserModel;
import one.stand.model.live.AttentionUserModel;
import one.stand.model.live.ShortVideoModel;
import one.stand.request.live.AttentionUserFrom;
import one.stand.request.live.ShortVideoDataForm;
import one.stand.service.AttentionUserService;
import one.stand.service.BaseService;
import one.stand.service.WxMessageService;
import one.stand.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author luoyang
 * @date 2020/5/20 11:50
 */
@Service
@Slf4j
@Transactional
public class AttentionUserServiceImpl  extends BaseService implements AttentionUserService {

    @Autowired
    protected WxMessageService wxMessageService;

    @Override
    @Transactional
    public ResultModel<Boolean> addAttentionUser(AttentionUserFrom request) {

        ShortVideoModel shortVideoModel = this.shortVideoMapper.queryById(request.getVideoId());

        AttentionUserModel model = attentionUserMapper.queryByUserId(request);
        if(model == null){
            model = new AttentionUserModel();
            model.setUserId(request.getUserId());
            model.setVideoId(request.getVideoId());
            model.setAttentionTime(DateUtil.now());
            model.setCompanyId(shortVideoModel.getCompanyId());
            if(request.getAttention() != null){
                model.setAttention(1);
            }
            if(request.getLike() != null){
                model.setIsLike(request.getLike());
            }
            if(this.attentionUserMapper.insert(model) > 0){
                updateLikesNum(request);
                ShortVideoModel oldModel = this.shortVideoMapper.queryById(request.getVideoId());


                this.sendUserMsg(oldModel.getUserId(),oldModel.getCompanyId());

                //已关注 表示增加或者更新
                if(oldModel != null && model.getAttention() != null && model.getAttention() == 1){
                    oldModel.setAttentionNum((oldModel.getAttentionNum() == null ? 0 : oldModel.getAttentionNum()) + 1);
                    oldModel.setGuestsNum((oldModel.getGuestsNum() == null ? 0 : oldModel.getGuestsNum()) + 1);
                    if(this.shortVideoMapper.update(oldModel) > 0){
                        return ResultModel.success();
                    }else{
                        return ResultModel.fail();
                    }

                }else if(oldModel != null ){
                    //更新获客人数
                    oldModel.setGuestsNum((oldModel.getGuestsNum() == null ? 0 : oldModel.getGuestsNum()) + 1);
                    if(this.shortVideoMapper.update(oldModel) > 0){
                        return ResultModel.success();
                    }else{
                        return ResultModel.fail();
                    }
                }
            }
            return ResultModel.success();
        }else{

            if(request.getAttention() != null){
                model.setAttention(request.getAttention());
            }
            if(request.getLike() != null){
                model.setIsLike(request.getLike());
            }

            if(request.getCId() != null){
                model.setCompanyId(shortVideoModel.getCompanyId());
            }
            if( request.getAttention() != null && request.getAttention() == 1){
                ShortVideoModel oldModel = this.shortVideoMapper.queryById(request.getVideoId());
                if(oldModel != null ){
                    //给名片用户发送订阅消息
                    this.sendUserMsg(oldModel.getUserId(),oldModel.getCompanyId());
                }
            }
            this.attentionUserMapper.update(model);
            updateLikesNum(request);
            return ResultModel.success();
        }

    }

    /**
     * 增加或减少点赞数 不能小于0
     * @param request
     */
    private void updateLikesNum(AttentionUserFrom request){
        if(request.getVideoId() != null && request.getLike() != null){
            ShortVideoModel oldModel = this.shortVideoMapper.queryById(request.getVideoId());
            if(request.getLike()){
                oldModel.setLikesNum(oldModel.getLikesNum() + 1 );
            }else{
                oldModel.setLikesNum(oldModel.getLikesNum() - 1 <= 0 ? 0 : oldModel.getLikesNum() - 1 );
            }
            this.shortVideoMapper.update(oldModel);
        }
    }


    /**
     * 发送给user端的客戶
     *
     * @return
     */
    @Async
    public void sendUserMsg(Integer toUserId,Integer companyId) {
        // 微信推送 未读消息
        UserModel userModel = this.userMapper.selectByPrimaryKey(toUserId);

        WxNoticeEntity entity = userMapper.getToSendUserTemplateInfo(toUserId);
        CompanyModel companyModel = this.companyMapper.selectByPrimaryKey(companyId);
        if(entity == null || companyModel == null){
            return;
        }
        //待处理 text 长度不能超过20
        String[] arr = {one.stand.util.StringUtils.formatName(companyModel.getCompanyName()),one.stand.util.StringUtils.formatName("有人关注了".concat(companyModel.getCompanyName())) , getDay(),"你有未读消息"};

        log.info("sendUserMsg={},userModel={},companyModel={}",entity,userModel,companyModel);
        wxMessageService.sendNewTemplate(userModel.getCrmOpenId(), entity.getUserFormId(), WxSubscribeEnums.UNREAD_MESSAGE_CRM, arr, LoginEnum.CRM.getAccountType(),companyId);
    }
}
